package com.miplus.ccrm.report.service;

import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class ExportService {
    private String GetCellValue(HashMap<String,Object> map, String key)
    {
        String ret="";
        for(String mkey : map.keySet()){
            if(JPubUtils.IsEqual(mkey,key)){
                ret=JPubUtils.ObjectToString(map.get(mkey));
                break;
            }
        }
        return ret;
    }

    public CmdResVo ToExcel(HttpServletResponse response, ArrayList<HashMap<?, ?>> arrList, List<String> colids, List<String> colnames, String outfilename, String $usrid)
    {
        int ret=arrList.size();
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmss");
        String batchid= $usrid + "." + sdf.format(new Date());

        String retfilename=outfilename;
        if(JPubUtils.IsEmpty(retfilename)){
            retfilename=sdf.format(new Date())+".xlsx";
        }

        log.info("ToExcel:count={},batchid={},outfilename={}",ret,batchid,retfilename);

        try{
            log.info("ToExcel:colids={},colnames={}",colids,colnames);
            Workbook workbook = new XSSFWorkbook();
            //在工作簿中创建一张表sheet
            Sheet sheet = workbook.createSheet("sheet1");
            Row row;
            row = sheet.createRow(0);
            for(int j=0;j<colnames.size();j++){
                row.createCell(j).setCellValue(colnames.get(j));
            }
            for (int i = 0; i < arrList.size(); i++) {
                row = sheet.createRow(i + 1);
                HashMap map=arrList.get(i);
                for(int j=0;j<colids.size();j++){
                    row.createCell(j).setCellValue(GetCellValue(map,colids.get(j)));
                }
            }
            arrList.clear();
            colids.clear();
            colnames.clear();

            log.info("ToExcel:create excel:{}",retfilename);
            //需要通过response给前端数据流，设置对应的response
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(retfilename,"utf-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            log.info("ToExcel:create excel Ok.");
        } catch (IOException e) {
            log.warn("ToExcel.Err",e);
            throw new ServiceException(EnumRCode.ExcelErr.value, e.getMessage());
        }

        return new CmdResVo(ret,batchid);
    }

    public Workbook AddExcel(Workbook workbook,String sheet1name,ArrayList<HashMap<?, ?>> arrList,List<String> colnames)
    {
        log.info("AddExcel:sheet={},count={}",sheet1name,arrList.size());

        Sheet sheet = workbook.createSheet(sheet1name);
        Row row=sheet.createRow(0);
        for(int j=0;j<colnames.size();j++){
            row.createCell(j).setCellValue(colnames.get(j));
        }
        for (int i = 0; i < arrList.size(); i++) {
            row = sheet.createRow(i + 1);
            HashMap map=arrList.get(i);
            for(int j=0;j<colnames.size();j++){
                row.createCell(j).setCellValue(GetCellValue(map,colnames.get(j)));
            }
        }

        log.info("AddExcel.Done");

        return workbook;
    }
}
